package com.itheima.service.impl;

import com.itheima.domain.entity.Salary;
import com.itheima.mapper.SalaryMapper;
import com.itheima.service.SalaryService;
import com.itheima.utils.CategoryUtil;
import com.itheima.utils.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class SalaryServiceImpl implements SalaryService {
    @Autowired
    private SalaryMapper salaryMapper;

    @Override
    public List<Salary> total() {
        List<Salary> total = salaryMapper.total();
        total.sort(new Comparator<Salary>() {
            @Override
            public int compare(Salary o1, Salary o2) {
                String s1 = o1.getSalary().replace("k", "");
                String s2 = o2.getSalary().replace("k", "");
                int n1=Integer.parseInt(s1);
                int n2=Integer.parseInt(s2);
                return n2-n1;
            }
        }.reversed());
        return total;
    }

    @Override
    public List<Salary> category(String category) throws SQLException {
        String tb = CategoryUtil.getCategory(category);
        List<Salary> result = query(category, tb);
        result.sort(new Comparator<Salary>() {
            @Override
            public int compare(Salary o1, Salary o2) {
                String s1 = o1.getSalary().replace("k", "");
                String s2 = o2.getSalary().replace("k", "");
                int n1=Integer.parseInt(s1);
                int n2=Integer.parseInt(s2);
                return n2-n1;
            }
        }.reversed());
        return result;
    }

    private static List<Salary> query(String category, String tb) throws SQLException {
        SqlUtil sqlUtil = new SqlUtil();
        String sql = "select * from " + tb + "_salary_analysis where category='" + category + "' and salary != '面议'";
        ResultSet resultSet = sqlUtil.executeQuery(sql);
        List<Salary> salaries = new ArrayList<>();
        while (resultSet.next()) {
            Salary build = Salary.builder()
                    .category(resultSet.getString("category"))
                    .salary(resultSet.getString("salary"))
                    .count(resultSet.getInt("count"))
                    .build();
            salaries.add(build);
        }
        sqlUtil.close();
        return salaries;
    }
}
